package cn.lbd.kill.server.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.amqp.SimpleRabbitListenerContainerFactoryConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class RabbitMQConfig {
    private final static Logger log = LoggerFactory.getLogger(RabbitMQConfig.class);

    @Autowired
    private Environment env;

    // 缓存连接工厂，连接mq的连接工厂
    @Autowired
    private CachingConnectionFactory connectionFactory;

    // 监听器，配置高并发时消费者实例基本参数
    @Autowired
    private SimpleRabbitListenerContainerFactoryConfigurer factoryConfigurer;

    /**
     * 单一消费者
     *
     * @return
     */
    @Bean(name = "singleListenerContainer")
    public SimpleRabbitListenerContainerFactory listenerContainer() {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        // 设置连接工厂
        factory.setConnectionFactory(connectionFactory);
        //设置消息转换器，因为传输的是java对象的话，要将其序列化，
        // 使用Jackson2JsonMessageConverter会比较有效
        factory.setMessageConverter(new Jackson2JsonMessageConverter());
        // 设置唯一消费者
        factory.setConcurrentConsumers(1);
        // 设置最多有多少消费者进行消费
        factory.setMaxConcurrentConsumers(1);
        // 设置每次消费多少条消息
        factory.setPrefetchCount(1);
        factory.setTxSize(1);
        return factory;
    }

    /**
     * 多个消费者
     *
     * @return
     */
    @Bean(name = "multiListenerContainer")
    public SimpleRabbitListenerContainerFactory multiListenerContainer() {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factoryConfigurer.configure(factory, connectionFactory);
        factory.setMessageConverter(new Jackson2JsonMessageConverter());
        //确认消费模式-NONE  默认的，不需要
        factory.setAcknowledgeMode(AcknowledgeMode.NONE);
        // 通过配置
        factory.setConcurrentConsumers(env.getProperty("spring.rabbitmq.listener.simple.concurrency", int.class));
        factory.setMaxConcurrentConsumers(env.getProperty("spring.rabbitmq.listener.simple.max-concurrency", int.class));
        factory.setPrefetchCount(env.getProperty("spring.rabbitmq.listener.simple.prefetch", int.class));
        return factory;
    }

    @Bean
    public RabbitTemplate rabbitTemplate() {
        connectionFactory.setPublisherConfirms(true);
        connectionFactory.setPublisherReturns(true);
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                log.info("消息发送成功:correlationData({}),ack({}),cause({})", correlationData, ack, cause);
            }
        });
        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
                log.warn("消息丢失:exchange({}),route({}),replyCode({}),replyText({}),message:{}", exchange, routingKey, replyCode, replyText, message);
            }
        });
        return rabbitTemplate;
    }

    /**
     * 构建异步发送邮箱通知的消息模型
     **/
    // 队列
    @Bean
    public Queue successEmailQueue() {
        return new Queue(env.getProperty("mq.kill.item.success.email.queue"), true);
    }

    // 交换机
    @Bean
    public TopicExchange successEmailExchange() {
        return new TopicExchange(env.getProperty("mq.kill.item.success.email.exchange"), true, false);
    }

    // 通过路由key绑定交换机与队列
    @Bean
    public Binding successEmailBinding() {
        return BindingBuilder.bind(successEmailQueue()).to(successEmailExchange()).with(env.getProperty("mq.kill.item.success.email.routing.key"));
    }

    /**
     * 构建秒杀成功之后-订单超时未支付的死信队列消息模型
     **/

    //死信队列(由死信交换机，死信路由和TTL组成)
    @Bean
    public Queue successKillDeadQueue() {
        Map<String, Object> argus = new HashMap<>();
        //死信交换机 key从MQ官网找
        argus.put("x-dead-letter-exchange", env.getProperty("mq.kill.item.success.kill.dead.exchange"));
        //死信路由  key从MQ官网找
        argus.put("x-dead-letter-routing-key", env.getProperty("mq.kill.item.success.kill.dead.routing.key"));
        //TTL在发送消息的后置处理器中编写
        return new Queue(env.getProperty("mq.kill.item.success.kill.dead.queue"), true, false, false, argus);
    }

    //死信交换机
    @Bean
    public TopicExchange successKillDeadExchange() {
        return new TopicExchange(env.getProperty("mq.kill.item.success.kill.dead.exchange"), true, false);
    }

    //真实队列
    @Bean
    public Queue successKillRealQueue() {
        return new Queue(env.getProperty("mq.kill.item.success.kill.dead.real.queue"), true);
    }

    //死信交换机，死信路由 => 真实队列   Binding
    @Bean
    public Binding successKillDeadBinding() {
        return BindingBuilder.bind(successKillRealQueue()).to(successKillDeadExchange()).with(env.getProperty("mq.kill.item.success.kill.dead.routing.key"));
    }

    //基本交换机
    @Bean
    public TopicExchange successKillDeadProdExchange() {
        return new TopicExchange(env.getProperty("mq.kill.item.success.kill.dead.prod.exchange"), true, false);
    }

    //基本交换机，基本路由 => 死信队列   Binding
    @Bean
    public Binding successKillDeadProdBinding() {
        return BindingBuilder.bind(successKillDeadQueue()).to(successKillDeadProdExchange()).with(env.getProperty("mq.kill.item.success.kill.dead.prod.routing.key"));
    }

}
